<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>Pie Multiples with Nesting Data form staff reward</title>
    <script type="text/javascript" src="../js/d3.js"></script>
    <script src="../js/dojo-release-1.9.3/dojo/dojo.js"></script>
    <script type="text/javascript" src="../util/Navigator.js"></script>
	<link rel="stylesheet" href="../js/dojo-release-1.9.3/dojo/resources/dojo.css">
	<link rel="stylesheet" href="../js/dojo-release-1.9.3/dijit/themes/claro/claro.css">
	<link rel="stylesheet" href="../js/dojo-release-1.9.3/dojox/grid/resources/claroGrid.css">
	<link rel="stylesheet" href="../css/navigator.css">
    <style type="text/css">
        body {
            text-align: center;
        }
        svg {
            font: 10px sans-serif;
        }
        
        div.gridTable {
			display: table;
			margin-left: 300px;
		}
		
		div.gridRow {
			display: table-row;
		}
		
		div.rightGrid {
			display: table-cell;
			padding-left: 20px;
		}
		div.leftGrid {
			display: table-cell;
			padding-right: 20px;
		}
		
		#divHeaderRow{
			font-size: 12px;
			font-weight: bold;
		}
        .header {
			font: 15px sans-serif;
		}
    </style>
</head>

<body class="claro">
	<div id="header" style="position: fixed;width: 100%;background-color: rgb(255,255,255);"></div>
	<div id="navigator" style="position: fixed;width: 100%;top: 42px;background-color: rgb(255,255,255);"></div>
    <script type="text/javascript">
         // Credit http://jsfiddle.net/7rDsC/ thank a lot Mr.Rattasit Sermsai
         // Load the data asynchronously.
        	var header = d3.select("#header").attr("class","header");
			header.html("<a href='../index.html'><img src='../images/home_icon.png'></a> สรุปรายการเครื่องาราชอิสริยาภรณ์ <br/>");

			var root = {"name":"ประเภทเครื่องราชอิสริยาภรณ์",
					"children":[{"name":"รายชื่อผู้ได้รับเครื่องราชอิสริยาภรณ์",
						"children":[{"name":"ประวัติการได้รับเครื่องราชอิสริยาภรณ์"}]
						}]
			};
			navigator("navigator", root);
			var navi = d3.select("#navigator").selectAll("g.node").selectAll("circle");
			var navi1,navi2,navi3;
			navi.forEach(function(d,i){
				if(i==0){
					navi1 = d[0];
				}else if(i==1){
					navi2 = d[0];
				}else{
					navi3 = d[0];
				}
			});
			navi1.style.fill = "rgb(176,196,222)";
        	
			d3.select("body").append("div").attr("id","donutChart");
			
			d3.json("../STF003Controller", function(error, data) {
            // Define the margin, radius, and color scale. Colors are assigned lazily, so
            // if you want deterministic behavior, define a domain for the color scale.
            var m = 100,
                r = 100,
                z = d3.scale.category20();

            var position = Math.PI / 180;

            // Define a pie layout: the pie angle encodes the count of reward. Since our
            // data is stored in json array, the counts are strings which we coerce to numbers.
            var pie = d3.layout.pie()
                .value(function(d) {
                    return +d.amount;
                })
                .sort(null);
            /*  .sort(function(a, b) {
                 return b.amount - a.amount;
             }); */

            // Define an arc generator. Note the radius is specified here, not the layout.
            var arc = d3.svg.arc()
                .innerRadius(r / 2)
                .outerRadius(r);

            // Nest the reward data by originating reward type. Our data has the counts per
            // reward name and reward type, but we want to group counts by reward type.
            var rewards = d3.nest()
                .key(function(d) {
                    return d.bytedes;
                })
                .entries(data);
            // Insert an svg element (with margin) for each reward in our dataset. A
            // child g element translates the origin to the pie center.
            var svg = d3.select("#donutChart").selectAll("div")
                .data(rewards)
                .enter()
                .append("div")
                .style("display", "inline")
                .style("width", 1024 + "px")
                .style("height", 768 + "px")
                .append("svg:svg")
                .attr("width", (r + m) * 2)
                .attr("height", (r + m) * 2)
                .append("svg:g")
                .attr("transform", "translate(" + (r + m) + "," + (r + m + 70) + ")");

            // Add a label for the reward type. The `key` comes from the nest operator.
            svg.append("svg:text")
                .attr("dy", ".35em")
                .attr("text-anchor", "middle")
                .text(function(d) {
                    return d.key;
                });

            // Pass the nested per-reward type values to the pie layout. The layout computes
            // the angles for each arc. Another g element will hold the arc and its label.
            var g = svg.selectAll("g")
                .data(function(d) {
                    return pie(d.values);
                })
                .enter().append("svg:g");

            // Add a colored arc path, with a mouseover title showing the count.

            g.append("svg:path")
                .attr("class", "arc")
                .style("fill", function(d) {
                    return z(d.data.rewardName);
                })
                .on("click",function(d) {firstDrilldown(d.data.rewardId,d.data.rewardName);})
                .transition()
                .ease("exp")
                .ease("bounce")
                .duration(2500)
                .delay(function(d, i) {
                    return i * 10;
                })
                .attrTween("d", tweenPie);

            function tweenPie(b) {
                var i = d3.interpolate({
                    startAngle: -30 * position,
                    endAngle: -31 * position
                }, b);
                return function(t) {
                    return arc(i(t));
                };
            }

            /* .transition().delay(function(d, i) { return i * 500; }).duration(500)
				.attrTween('d', function(d) {
				     var i = d3.interpolate(d.startAngle+0.1, d.endAngle);
				     return function(t) {
				         d.endAngle = i(t);
				       return arc(d);
				     }
				}); */
            /* .append("svg:title")
            .text(function(d) {
                return d.data.rewardName + ": " + d.data.amount;
            }); */
            var pos = d3.svg.arc().innerRadius(r + 50).outerRadius(r + 50);
            //line for label
            var ticks = svg.selectAll("line")
                .data(function(d) {
                    return pie(d.values);
                })
                .enter()
                .append("line");
            ticks.attr("x1", 0)
                .attr("x2", 0)
                .attr("y1", -r + 4)
                .attr("y2", -r - 15)
                .attr("stroke", "gray")
                .transition()
                .ease("exp")
                .ease("bounce")
                .duration(2500)
                .attr("transform", function(d) {
                    return "rotate(" + (d.startAngle + d.endAngle) / 2 * (180 / Math.PI) + ")";
                });

            //circle for label
            // Add a label to the larger arcs, translated to the arc centroid and rotated.
            g.append("svg:text")
                .attr("dy", ".35em")
                .attr("text-anchor", "middle")
                //.attr("transform", function(d) {return "translate(" + pos.centroid(d) + ")";})
                .text(function(d) {
                    return d.data.rewardName;
                })
                .transition()
                .ease("exp")
                .ease("bounce")
                .duration(2500)
                .delay(function(d, i) {
                    return i * 10;
                })
                .attrTween("transform", tweenText);

            function tweenText(b) {
                var i = d3.interpolate({
                    startAngle: -30 * position,
                    endAngle: -31 * position
                }, b);
                return function(t) {
                    return "translate(" + pos.centroid(i(t)) + ")";
                };
            }

            g.append("svg:text")
                .attr("dy", ".35em")
                .attr("text-anchor", "middle")
                //.attr("transform", function(d) {return "translate(" + arc.centroid(d) + ")";})
                .text(function(d) {
                    return d.data.amount;
                })
                .transition()
                .ease("exp")
                .ease("bounce")
                .duration(2500)
                .delay(function(d, i) {
                    return i * 10;
                })
                .attrTween("transform", tweenAmount);

            function tweenAmount(b) {
                var i = d3.interpolate({
                    startAngle: -30 * position,
                    endAngle: -31 * position
                }, b);
                return function(t) {
                    return "translate(" + arc.centroid(i(t)) + ")";
                };
            }

            // Computes the label angle of an arc, converting from radians to degrees.
            /*  function angle(d) {
               var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
               return a > 90 ? a - 180 : a;
             }*/
             
        });
    
      	//begin dojo section
        function drilldown(rewardId,rewardName){
			d3.json("../STF003Controller?criteria=rewardId&p1="+rewardId, function(error, data) {
				require([
							"dojox/grid/DataGrid",
							"dojo/store/Memory",
							"dojo/data/ObjectStore",
							"dojo/request",
							"dijit/Dialog",
							"dojo/dom-construct",
							"dojo/domReady!"
						], function(DataGrid, Memory, ObjectStore, request,Dialog,domConstruct){
								var dialog = dijit.byId('dialog');
								if(!dialog){
									dialog = new Dialog({
								      id:'dialog',
								      //title:'รายชื่อบุคลากร',
								      onCancel: function(){
									    	  if(dojo.byId("detailChart")){
									    	  	dojo.byId("detailChart").remove();
									    	  }
								    	  },
								      style:'width:510px; height:auto;'
								    }); 
								}
								dialog.set("title",rewardName);
								dialog.show();
								
								var grid = dijit.byId('dialogGrid');
								
								var dataStore =  new ObjectStore({ objectStore:new Memory({ data: data}) });
								if(!grid){
									grid = new DataGrid({
									id:"dialogGrid",
									query: { id: "*" },
									structure: [
									    { name: "ลำดับ", field: "rowNum" ,width: "30px"},
										{ name: "ชื่อ", field: "staffName", width: "150px" },
										{ name: "วันที่รับ", field: "receiveDate", width: "100px" }
									],
									style:'width:490px;height:400px;'
									});
								}
							 domConstruct.place(grid.domNode, dialog.containerNode,'first');
							 grid.setStore(dataStore);
							 grid.startup();
						});
			});
        }//end drilldown
      	
      	function firstDrilldown(rewardId,rewardName){
      		navi2.style.fill = "rgb(176,196,222)";
        	navi3.style.fill = "rgb(255,255,255)";
      		if(document.getElementById('gridTable')==null){
	        	var svg = d3.select("body")
						.append("div")
						.attr("id","gridTable")
						.attr("class","gridTable");
						
					svg = d3.select("#gridTable")
						.append("div")
						.attr("id","divHeaderRow")
						.attr("class","gridRow")
						
						.append("div")
						.attr("class","leftGrid")
						.append("div")
						.attr("id","haederLeftGrid");
					
					svg = d3.select("#divHeaderRow") 
						.append("div")
						.attr("class","rightGrid")
						.append("div")
						.attr("id","haederRightGrid");	
					
					svg = d3.select("#gridTable")
						.append("div")
						.attr("id","divGridRow")
						.attr("class","gridRow")
						
						.append("div")
						.attr("class","leftGrid")
						
						.append("div")
						.attr("id","firstGrid");
	        	
	        		svg = d3.select("#divGridRow")
		    			.append("div")
		    			.attr("class","rightGrid")
		    			
		    			.append("div")
		    			.attr("id","secondGrid");
	        		
	        		//set name of reward into header grid
	        		document.getElementById("haederLeftGrid").innerHTML=rewardName; 
        	}else{
        		//set name of reward into header grid
        		document.getElementById("haederLeftGrid").innerHTML=rewardName; 
        		document.getElementById('haederRightGrid').innerHTML = '';
        		document.getElementById('secondGrid').style.display = 'none';
        	}
        	/* var svg = d3.select("body")
        			.append("div")
        			.attr("id","divGrid")
        			.style("width","1500px")
        			.style("margin","auto");
        			
        	
        		svg = d3.select("#divGrid")
        			.append("div")
        			.attr("id","fistGrid"); */
        	
      		d3.json("../STF003Controller?criteria=rewardId&p1="+rewardId, function(error, data) {
	      		require([
	 					"dojox/grid/DataGrid",
	 					"dojo/store/Memory",
	 					"dojo/data/ObjectStore",
	 					"dojo/request",
	 					"dijit/Dialog",
	 					"dojo/domReady!"
	 				], function(DataGrid, Memory, ObjectStore, request){
	      				var grid = dijit.byId('firstGrid');
	 					var	dataStore =  new ObjectStore({ objectStore:new Memory({ data: data}) });
	 					if(!grid){
		 					grid = new DataGrid({
	 							store: dataStore,
	 							id:"firstGrid",
	 							query: { id: "*" },
	 							structure: [
	 								 { name: "ลำดับ", field: "rowNum" ,width: "30px"},
									 { name: "ชื่อ", field: "staffName", width: "150px" },
									 { name: "วันที่รับ", field: "receiveDate", width: "80px",
										 formatter: function(receiveDate){
											 var date = new Date(receiveDate); 
											 return date.toLocaleDateString("th-TH");}},
	 							],
	 							style:'width:320px; height:400px;'
	 						}, "firstGrid");
	 					}
 						grid.setStore(dataStore);
 						grid.startup();
 						
 						var idx,itm,value;
						dojo.connect(grid, "onRowClick", grid, function(evt){
							idx = evt.rowIndex;
							item = this.getItem(idx);
							value = this.store.getValue(item,"staffId");
							secondDrilldown(value);
						});
	 				});
      		});
      		goToAnchor("firstGrid");
      	}//end firstDrilldowwn
      	
      	function secondDrilldown (staffId){
      		navi3.style.fill = "rgb(176,196,222)";
      		/* var svg = d3.select("#divGrid")
        			.append("div")
        			.attr("id","secondGrid"); */
      		
      		/* svg = d3.select("#divGrid")
        			.append("div")
        			.attr("id","blockGrid2")
        			.style("display","inline-block")
        			.append("div")
        			.attr("id","secondGrid") */
        			
    		/* .append("div")
    		.attr("id","secondGrid")
        	.style("display", "inline")
        	.style("magin-left","auto")
        	.style("magin-right","auto"); */
    	
  			d3.json("../STF003Controller?criteria=staffId&p1="+staffId, function(error, data) {
  				document.getElementById("haederRightGrid").innerHTML= "ประวัติการรับเครื่องราชอิสริยาภรณ์ "+data[0].staffName;
  				document.getElementById('secondGrid').style.display = 'block';
	      		require([
	 					"dojox/grid/DataGrid",
	 					"dojo/store/Memory",
	 					"dojo/data/ObjectStore",
	 					"dojo/request",
	 					"dijit/Dialog",
	 					"dojo/domReady!"
	 				], function(DataGrid, Memory, ObjectStore, request){
	      				var grid = dijit.byId('secondGrid');
	 					var	dataStore =  new ObjectStore({ objectStore:new Memory({ data: data}) });
	 					if(!grid){
		 					grid = new DataGrid({
	 							store: dataStore,
	 							id:"secondGrid",
	 							query: { id: "*" },
	 							structure: [
	 								 { name: "ลำดับ", field: "rowNum" ,width: "30px"},
									 { name: "ชื่อ", field: "staffName", width: "150px" },
									 { name: "วันที่รับ", field: "receiveDate", width: "80px",
										 formatter: function(receiveDate){
											 var date = new Date(receiveDate); 
											 return date.toLocaleDateString("th-TH");}},
									 { name: "เครื่องราษฏ์", field: "rewardName", width: "140px" }
	 							],
	 							style:'width:470px;height:400px;'
	 						}, "secondGrid");
	 					}
						grid.setStore(dataStore);
						grid.startup();
							
	 				});
	  		});
      	}//end secondeDrilldown
      	
      	function goToAnchor(name) {
            document.getElementById(name).scrollIntoView(true);
        }
      	
      	/* var date = new Date("Dec 5, 2012 12:00:00 AM");
      	var options = {
      		    weekday: "long",
      		    year: "numeric",
      		    month: "long",
      		    day: "numeric"
      		};
      	console.log(date);
      	console.log(date.toLocaleDateString());
      	console.log(date.toLocaleDateString("th-u-ca-buddhist-nu-thai", options)); */
    </script>
</body>

</html>